<template>
	<el-dialog :title="title" v-model="dialogVisible" class="redius8" width="1200" center :before-close="handleClose">
		<el-form :model="form" :rules="rules" ref="queryRef" :inline="true" label-width="106px">
			<div class="bgWhite radius8 pb30">
				<div class="p20">
					<div class=" fb color333 fs16 line-64 mb10">
						{{form.id == '' ? '新建' : '编辑'}}配方
					</div>
					<el-form-item label="商品名称" prop="commodityName">
						<el-input size="large" @click="showGoods" readonly v-model="form.commodityName"
							style="width: 248px" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="农药登记证号" prop="pesticideRegistrationNumber">
						<el-input size="large" v-model="form.pesticideRegistrationNumber" style="width: 248px"
							placeholder="请输入" />
					</el-form-item>
					<el-form-item label="商品规格" prop="productSpecification" style="margin-right: 0;">
						<el-input v-model="form.productSpecification" placeholder="请输入" class="input-with-select"
							size="large" style="width: 248px;">
							<template #append>
								<el-select size="large" v-model="form.productSpecificationUnit" placeholder="请选择"
									style="width: 94px;">
									<el-option v-for="dict in bus_active_ingredient_content" :key="dict.value"
										:label="dict.label" :value="dict.value" />
								</el-select>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item label="库存价" prop="inventoryCost">
						<el-input size="large" v-model="form.inventoryCost" style="width: 248px"
							placeholder="请输入" />
					</el-form-item>
				</div>
				<div class="pl20 mt30 flex col-center row-between pr20">
					<div>
						<span class="fb color333 fs16">商品配方</span>
						<div class="color-red fs14 mt10" v-if="form.productMaterialMappings.length > 0">
							{{date}} 最新实时成本：{{form.realTimeCost || 0}}元/吨
						</div>
					</div>
					<el-button type="defaultBtn" @click="handleAdd()" style="width: 86px;">
						添加原材料
					</el-button>
				</div>
				<div class="p20">
					<el-table :data="form.productMaterialMappings" style="width: 100%;text-align: center;"
						:cell-style="{ textAlign: 'center','line-height':'54px'}" ref="form"
						:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }">
						<el-table-column prop="materialName" label="成本名称" />
						<el-table-column prop="materialId" label="ID" />
						<el-table-column prop="materialPercentage" label="原药含量占比（%）">
							<template v-slot="scope">
								<el-form-item style="margin-right: 0;margin-top: 18px;">
									<el-input type="number" v-model="scope.row.materialPercentage" style="width: 120px"
										size="large" placeholder="请输入" />
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column prop="latestPrice" label="最新价格（元/吨）" />
						<el-table-column fixed="right" label="操作" align="center" width="200">
							<template v-slot="scope">
								<el-button size="mini" type="text" @click="delRecipe(scope.$index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-form-item label="备注信息" prop="remark" class="mt20" style="width: 100%;" label-width="68px">
						<el-input v-model="form.remark" class="radius8" style="box-shadow: none;" show-word-limit
							:rows="5" type="textarea" placeholder="请输入备注信息" resize="none"
							:input-style="{background:'#F7F8FA',borderRaduis:'15px',boxShadow:'none'}" />
					</el-form-item>
				</div>
				<div class="text-center" style="margin-top: 30px;">
					<el-button type="defaultBtn" @click="submitProduct('queryRef')" style="height: 38px;width: 88px;">
						{{form.id == '' ? '创建配方' : '保存'}}
					</el-button>
					<el-button type="operate" style="width: 88px;height: 38px;" @click="resetQuery()">重置</el-button>
					<el-button style="width: 88px;height: 38px;"
						@click="dialogVisible = false">取 消</el-button>
				</div>
			</div>
		</el-form>
		<!-- 商品弹窗 -->
		<goodsPop ref="goodsDialog" @goodsVal="goodsVal"></goodsPop>
		<!-- 原材料弹窗 -->
		<rawPop ref="raw" @checkData="checkData" :idArr="idArr"></rawPop>



	</el-dialog>
</template>

<script>
	// 商品弹窗
	import goodsPop from './goods.vue'
	//原材料弹框
	import rawPop from './raw.vue'
	import {
		productRecipeAddInfo, //新增
		costListDetail, //详情
		productRecipeEditInfo //编辑
	} from "@/api/business/cost";
	import {
		getDivisions
	} from "@/api/business/opportunity"; //地址
	import {
		resetForm,
	} from '@/utils/ruoyi' //重置
	export default {
		components: {
			goodsPop,
			rawPop
		},
		data() {
			return {
				bus_active_ingredient_content: this.useDict('bus_active_ingredient_content').bus_active_ingredient_content,
				title:'',
				dialogVisible:false,
				form: {
					commodityId: "", //商品id
					commodityName: '', //商品名称
					pesticideRegistrationNumber: "", ///农药登记号
					productSpecification: "", //商品规格值
					productSpecificationUnit: "1001", //商品规格单位,来自字典bus_active_ingredient_content
					realTimeCost: "", //实时成本
					updateTime: "", //更新时间
					productMaterialMappings: []
				},
				rules: {
					commodityName: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}],
					pesticideRegistrationNumber: [{
						required: true,
						message: '请输入农药登记证号',
						trigger: 'blur'
					}],
					productSpecification: [{
						required: true,
						message: '请输入商品规格',
						trigger: 'blur'
					}],
					materialPercentage: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}],
					inventoryCost:[{
						required: true,
						message: '请输入库存价',
						trigger: 'blur'
					}]
				},
				date: this.getCurrentDate(),
				price: 0,
				disabled:'',
				idArr:[],//选中的原料
			}
		},
		// created() {
		// 	this.form.id = this.$route.query.id ? this.$route.query.id : ''
		// 	if (this.form.id != '') {
		// 		const obj = Object.assign({}, this.$route, {
		// 			title: "编辑配方"
		// 		});
		// 		this.$tab.updatePage(obj);
		// 		this.getDetail()
		// 	} else {
		// 		const obj = Object.assign({}, this.$route, {
		// 			title: "新建配方"
		// 		});
		// 		this.$tab.updatePage(obj);
		// 	}
		// },
		methods: {
			handleClose(){
				this.dialogVisible = false
			},
			open(num,disabled){
				this.disabled = disabled
				if(this.resetQuery()){
					if(num == ''){
						this.title = '新建配方'
						this.form.id = ''
					}else if(num !='' && !disabled){
						this.title = '编辑配方'
						this.form.id = num
						this.getDetail()
					}else{
						this.title = '配方详情'
						this.form.id = num
						this.getDetail()
					}
					this.dialogVisible = true
				}
			},
			getCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = this.padNumber(now.getMonth() + 1); // 月份是从0开始的
				const day = this.padNumber(now.getDate());
				return `${year}-${month}-${day}`;
			},
			padNumber(num) {
				return num < 10 ? '0' + num : num;
			},
			// 选择商品
			showGoods() {
				this.$refs.goodsDialog.open()
			},
			// 选中的商品
			goodsVal(e) {
				this.form.commodityId = e.id
				this.form.commodityName = e.commodityName
				this.$refs.goodsDialog.close()
			},
			//新增原材料
			handleAdd() {
				let arr = []
				for(let key in this.form.productMaterialMappings){
					arr.push(this.form.productMaterialMappings[key].materId)
				}
				this.idArr = arr
				console.log(arr,'arr======')
				this.$refs.raw.open()
			},
			// 选中的原材料
			checkData(e) {
				console.log(e,'ee==d==dd=')
				for (let key in e) {
					e[key].materId = e[key].id
					e[key].id = ''
					e[key].materialPercentage = ''
				}
				this.form.productMaterialMappings = this.form.productMaterialMappings.concat(e)

				this.countPrice()
			},
			// 删除
			delRecipe(index) {
				this.form.productMaterialMappings.splice(index, 1)
				this.countPrice()
			},
			closePage() {
				this.$tab.closePage();
			},
			// 重置
			resetQuery() {
				this.form = {
					commodityId: "", //商品id
					commodityName: '', //商品名称
					pesticideRegistrationNumber: "", ///农药登记号
					productSpecification: "", //商品规格值
					productSpecificationUnit: "1001", //商品规格单位,来自字典bus_active_ingredient_content
					realTimeCost: "", //实时成本
					updateTime: "", //更新时间
					productMaterialMappings: []
				}
				for (let key in this.form.productMaterialMappings) {
					this.form.productMaterialMappings[key].materialPercentage = ''
				}
				this.$forceUpdate()
				return true
			},
			// 详情
			getDetail() {
				costListDetail(this.form.id).then(res => {
					this.form = res.data
					this.form.commodityName = res.data.productName
					this.countPrice()
				})
			},
			countPrice() {
				let price = 0
				for (let key in this.form.productMaterialMappings) {
					price += this.form.productMaterialMappings[key].latestPrice * 1
				}
				this.price = price
			},
			//添加
			submitProduct(formName) {
				console.log(this.form, 'form')
				if (this.form.productMaterialMappings.length == 0) {
					this.$modal.msgError("请添加原材料");
					return false
				}
				let a = 0
				for (let key in this.form.productMaterialMappings) {
					if (this.form.productMaterialMappings[key].materialPercentage == '') {
						a += 1
					}
				}
				if (a > 0) {
					this.$modal.msgError("请输入原料含量占比");
					return false;
				}
				
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// 新增
						if (this.form.id == '') {
							productRecipeAddInfo(this.form).then(response => {
								this.$modal.msgSuccess('添加成功')
								this.dialogVisible = false
								this.$emit('refreshList')
								// setTimeout(() => {
								// 	this.closePage()
								// 	this.$router.go(-1)
								// }, 1500)
							})
						} else {
							// 编辑
							productRecipeEditInfo(this.form).then(response => {
								this.$modal.msgSuccess('编辑成功')
								this.dialogVisible = false
								this.$emit('refreshList')
								// setTimeout(() => {
								// 	this.closePage()
								// 	this.$router.go(-1)
								// }, 1500)
							})
						}
					} else {
						return false;
					}
				});
			},

		}
	}
</script>

<style>
	.avatar-uploader .el-upload {
		background: #F7F8FA;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 110px;
		height: 110px;
		text-align: center;
		line-height: 22px;
		color: #8c939d;
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
	}

	.shopImg {
		width: 110px;
		height: 110px;
	}
</style>